package com.vinobase.controller.management;

import com.vinobase.model.bean.Culture;
import com.vinobase.model.dao.CultureDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.SortedSet;

@Controller
@RequestMapping(value="/management/culture")
public class CultureController {

    @Autowired
    private CultureDao dao;

    @ModelAttribute("cultures")
    public SortedSet<Culture> populateCountries() {
        return dao.getList();
    }

    @RequestMapping(value="/create.html", method= RequestMethod.GET)
    protected String getCreateForm(Model model){
        model.addAttribute(new Culture());
        return "management/culture/create";
    }

    @RequestMapping(value="/list.html")
    protected String getList() {
        return "management/culture/list";
    }


    @RequestMapping(value="/create.html", method=RequestMethod.POST)
    protected String create(@Valid Culture culture, BindingResult result, Model model){
        if (result.hasErrors()) {
                    return "management/culture/create";
        }
        dao.create(culture);
        model.addAttribute("cultures",dao.getList());
        return "management/culture/list";
    }

    @RequestMapping(value="/{id}.html", method=RequestMethod.GET)
    protected String view(@PathVariable Long id, Model model){
        model.addAttribute("culture",dao.get(id));
        return "management/culture/create";
    }

    @PreAuthorize("hasRole('Admin')")
    @RequestMapping(value="/delete.html", method=RequestMethod.GET)
    protected String delete(HttpServletRequest request, Model model){
        dao.delete(Long.parseLong(request.getParameter("id")));
        model.addAttribute("cultures",dao.getList());
        return "management/culture/list";

    }

}
